{"componentChunkName":"component---src-templates-post-jsx","path":"/[BackEnd]Sync&aSync/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"fa6720c2-ab20-5a55-b914-bbf10ec8fda0","excerpt":"동기처리 및 비동기처리에 대해 정리하는 POST입니다. 백엔드 개발을 수행하면서, (사실 이전에 프론트 개발 시에도) 동기처리, 비동기처리라는 용어를 많이 봤지만, 정확하게 이해하고 넘어가진 않았다. 이 POST를 계기로 정확하게 이해하고 앞으로 적용할 수 있도록 한다. \"기본적으로 함수는 선언된 시기가 아닌 호출되는 시기에 동작한다.\" 💡 동기, 비동기…","html":"<p><em>동기처리 및 비동기처리에 대해 정리하는 POST입니다.</em></p>\n<p>백엔드 개발을 수행하면서, (<del>사실 이전에 프론트 개발 시에도</del>) <strong>동기처리</strong>, <strong>비동기처리</strong>라는 용어를 많이 봤지만, 정확하게 이해하고 넘어가진 않았다. 이 POST를 계기로 정확하게 이해하고 앞으로 적용할 수 있도록 한다.</p>\n<p>\"기본적으로 함수는 선언된 시기가 아닌 <strong>호출되는 시기</strong>에 동작한다.\"</p>\n<h2>💡 동기, 비동기 처리란?</h2>\n<p>동기와 비동기는 <strong>\"프로세스의 수행 순서 보장에 대한 매커니즘\"</strong>이다.</p>\n<h3>☺️ 동기 (Synchronous)</h3>\n<p>동시에 일어난다는 의미\n즉, <strong>요청과 그 결과가 동시에 일어난다</strong>는 약속인데, 요청을 하면, 시간이 얼마가 걸리던지 요청한 자리에서 바로 결과가 주어져야 하고, 결과를 받은 이후 다음 요청이 가능하다.</p>\n<p>코드측면에서 쉽게 이해하자면, <strong>프로그램이 작성된 순서대로 실행되는 것</strong>이라고 할 수 있다.</p>\n<p><strong>예시</strong> : \"은행 계좌의 돈을 송금하는 과정\"</p>\n<ul>\n<li>A의 계좌에서 돈을 송금, B의 계좌에 입금</li>\n<li>B의 계좌에 입금이 완료된 경우, A의 계좌에서 출금</li>\n<li>A의 계좌의 출금과 B의 계좌의 입금이 <strong>동시에 발생</strong></li>\n</ul>\n<p>위의 과정이 동기적으로 일어나야 문제가 발생하지 않는다. 따라서 동기처리가 이뤄져야 한다.</p>\n<h3>😇 비동기 (Asynchronous)</h3>\n<p>동기와 반대의미로, 동시에 일어나지 않는다는 의미\n즉 요청과 결과가 동시에 일어나지 않을 거라는 약속이다. 요청을 하면, 그 자리에서 결과가 주어지지 않는다. 따라서, 요청에 대한 결과를 전달받지 않고 다음 요청을 수행할 수 있다.</p>\n<p>코드측면에서 쉽게 이해하자면, <strong>프로그램이 작성된 순서대로 실행되지 않고 독자적인 흐름이 생기는 것</strong>이라고 할 수 있다.</p>\n<p><strong>예시</strong> : \"시험치는 학생과 교사\"</p>\n<ul>\n<li>학생은 시험지를 풀고 제출</li>\n<li>교사는 시험지는 채점하고 학생에게 전달</li>\n</ul>\n<p>위의 과정은 동기적으로 이뤄지지 않아도 되기에 비동기처리가 가능하다.</p>\n<h3>🙃 장, 단점</h3>\n<p><strong>동기</strong></p>\n<ul>\n<li>설계가 매우 간단하고 직관적</li>\n<li>결과가 주어질 때까지 다른 작업을 수행하지 못하고 대기해야 한다.</li>\n</ul>\n<p><strong>비동기</strong></p>\n<ul>\n<li>동기보다 복잡</li>\n<li>결과가 주어지는데 시간이 걸리더라도 그 시간동안 다른 작업을 수행할 수 있으므로 효율적인 자원의 사용이 가능하다.</li>\n</ul>\n<hr>\n<h2>💡 Callback</h2>\n<p>다른 함수에 인자로서 전달되는 함수로, 호출방식에 의한 구분으로 붙은 이름이다.\n특정 함수에 전달되어, 특정 함수 내에서의 어떠한 조건(또는 Event)에 의해 호출된다.</p>\n<p><strong>특정 함수에 전달</strong></p>\n<deckgo-highlight-code language=\"javascript\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">function printFirst() {\n    console.log(&#39;hello&#39;);\n}\n\nfunction printSecond() {\n    console.log(&#39;bye&#39;);\n}\n\nfunction sleepAndExec(sleepTime, callback) {\n    sleep(sleepTime);\n    callback();\n}\n\nsleepAndExec(3, printFirst);\nsleepAndExec(5, printSecond);</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">sleepAndExec()</code> 는 대기 시간과 호출할 함수를 지정하여 사용할 수 있다.</li>\n<li><code class=\"language-text\">sleepAndExec(3, printFirst);</code> 에서 <code class=\"language-text\">printFirst</code> 는 <code class=\"language-text\">sleepAndExec()</code> 의 인자로 전달되기에 <strong>Callback 함수</strong>이다.</li>\n</ul>\n<p><strong>어떠한 조건(또는 Event)</strong></p>\n<deckgo-highlight-code language=\"javascript\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">function onDetected() {\n    console.log(&quot;감지!&quot;);\n}\n\nsetOnDetected(onDetected);</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">setOnDetected</code> 로 설정한 <code class=\"language-text\">onDetected</code> 가, 특정 조건이 감지되었을 때마다 호출되기에 이는 <strong>Callback 함수</strong>이다.</li>\n</ul>\n<p>이러한 Callback은 <strong>Non-block</strong>이며, <strong>비동기 (Asynchronous) 방식의 함수</strong>로 사용된다.</p>\n<ul>\n<li>Callback을 전달하고, 바로 실행되는 것이 아니기 때문에 비동기 방식으로 사용된다.</li>\n</ul>\n<deckgo-highlight-code language=\"javascript\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">tmp = function(a, b, callback) {\n    callback(a+b, a-b);\n}\n\ntmp(1, 2, function(x, y) {\n    console.log(x);\n    console.log(y);\n})\n\n// output\n3\n-1</code>\n        </deckgo-highlight-code>\n<h3>🤪 이유</h3>\n<p>Javascript는 현재 <strong>비동기식 프로그래밍</strong>을 사용하고 있다.\n이는 모든 요청을 실행하고 결과를 받는 순서대로 다음 요청을 수행하는 방식이므로, 자원의 낭비를 줄인다.</p>\n<p>이러한 비동기 프로그래밍을 처리하기 위해 <strong>Callback 함수</strong>가 사용된다.</p>\n<hr>\n<h2>💡 Promise</h2>\n<p>Callback의 원리를 이용해서 만든 라이브러리로, 비동기 처리에 사용하기 위해 <code class=\"language-text\">Promise 객체</code> 를 생성한다.</p>\n<blockquote>\n<p><strong>\"내용은 실행되었지만, 결과는 아직 반환하지 않은 객체\"</strong></p>\n</blockquote>\n<h3>🥺 상태</h3>\n<p><strong>Pending</strong> (대기), <strong>Fulfilled</strong> (이행), <strong>Rejected</strong> (실패)</p>\n<ul>\n<li>비동기 처리가 완료되지 않았다면 → <strong>Pending</strong> </li>\n<li>완료되었다면 → <strong>Fulfilled</strong></li>\n<li>실패하거나 오류가 발생했다면 → <strong>Rejected</strong></li>\n</ul>\n<deckgo-highlight-code language=\"javascript\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">const condition = true;\nconst promise = new Promise((resolve, reject) =&gt; {\n  if (condition) {\n    resolve(&#39;resolved&#39;);\n  } else {\n    reject(&#39;rejected&#39;);\n  }\n});\n\npromise\n  .then((res) =&gt; {\n    console.log(res);\n  })\n  .catch((error) =&gt; {\n    console.error(error);\n  });</code>\n        </deckgo-highlight-code>\n<ul>\n<li>\n<p><code class=\"language-text\">condition</code> 값에 따라 <code class=\"language-text\">promise</code> 의 반환 값이 결정된다.</p>\n<ul>\n<li>값이 <code class=\"language-text\">참</code> 인 경우 <code class=\"language-text\">resolve</code> 를 호출하고, <code class=\"language-text\">거짓</code> 인 경우 (또는 에러가 발생한 경우) <code class=\"language-text\">reject</code> 를 호출한다.</li>\n<li>따라서, 한 <code class=\"language-text\">Promise 객체</code> 에 <code class=\"language-text\">resolve</code> 와 <code class=\"language-text\">reject</code> 가 동시에 존재할 수 없다.</li>\n</ul>\n</li>\n<li><code class=\"language-text\">then</code> 을 통해 <code class=\"language-text\">resolove</code> 된 경우의 반환 값을 받을 수 있고, <code class=\"language-text\">catch</code> 를 통해 <code class=\"language-text\">reject</code> 된 경우의 반환 값을 받을 수 있다.</li>\n<li><code class=\"language-text\">then</code>, <code class=\"language-text\">catch</code> 의 chaining을 통해 비동기 로직의 성공 여부에 따른 분기 처리가 가능하다.</li>\n</ul>\n<hr>\n<h2>💡 async, await</h2>\n<p>가장 최근의 비동기 처리 문법으로, 기존의 <strong>Callback</strong> 이나 <strong>Promise</strong>의 단점을 해소하고자 만들어졌다.</p>\n<p>기존의 방식의 단점은 꼬리에 꼬리를 무는 chaining 코드가 나올 수 있어 <strong>콜백 지옥</strong>, <strong><code class=\"language-text\">then</code> 지옥</strong>이 만들어질 수 있다는 점이다.</p>\n<h3>😠 사용 방식</h3>\n<p><code class=\"language-text\">await</code> 를 통해 <code class=\"language-text\">Promise</code> 객체의 반환 값을 받아올 수 있다.</p>\n<p><code class=\"language-text\">async/await</code> 사용 시, <strong>\"<code class=\"language-text\">await</code> 는 <code class=\"language-text\">async</code> 함수 안에서만 동작한다\"</strong>는 점을 인지해야 한다.</p>\n<p><strong>예시</strong></p>\n<deckgo-highlight-code language=\"javascript\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">(async () =&gt; {\n  const condition = true;\n  const promise = new Promise((resolve, reject) =&gt; {\n    if (condition) {\n      resolve(&#39;resolved&#39;);\n    } else {\n      reject(&#39;rejected&#39;);\n    }\n  });\n\n  try {\n    const result = await promise;\n    console.log(result);\n  } catch (err) {\n    console.error(err);\n  }\n})();</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">async</code> 함수 내의 <code class=\"language-text\">await</code> 를 통해 <code class=\"language-text\">Promise</code> 의 반환 값을 <code class=\"language-text\">result</code> 에 담아 출력한다.</li>\n<li>주의할 점으로는 <code class=\"language-text\">Promise</code> 에서의 <code class=\"language-text\">then &amp; catch</code> 와 같은 <strong>Error Handling</strong>이 없어 <code class=\"language-text\">try-catch</code> 문을 활용해야 한다는 점이다.</li>\n</ul>\n<hr>\n<h2>💡 정리</h2>\n<p><strong>Error Handling</strong></p>\n<ul>\n<li><code class=\"language-text\">Promise</code> 는 <code class=\"language-text\">then &amp; catch</code> 문으로 Error Handling이 가능하다.</li>\n<li><code class=\"language-text\">async &amp; await</code> 는 이러한 기능이 없어 <code class=\"language-text\">try-catch</code> 문을 활용해야 한다.</li>\n</ul>\n<p><strong>Code 가독성</strong></p>\n<ul>\n<li><code class=\"language-text\">Promise</code> 는 콜백 지옥과 같은 <code class=\"language-text\">then</code> 지옥이 만들어질 수도 있다.</li>\n<li><code class=\"language-text\">async &amp; await</code> 는 코드 길이나 가독성 측면에서 효율적이고 흐름을 이해하는 데도 좋다.</li>\n</ul>\n<hr>\n<h2>📕 참고</h2>\n<p>동기, 비동기 처리란?</p>\n<ul>\n<li><a href=\"https://private.tistory.com/24\">동기와 비동기의 개념과 차이</a></li>\n<li><a href=\"https://evan-moon.github.io/2019/09/19/sync-async-blocking-non-blocking/\">동기는 정확히 무엇을 의미하는 걸까?</a></li>\n</ul>\n<p>Callback</p>\n<ul>\n<li><a href=\"https://lunuloopp.tistory.com/entry/%EB%8F%99%EA%B8%B0-%EB%B9%84%EB%8F%99%EA%B8%B0%EC%9D%98-%EC%9D%B4%ED%95%B4-callback%ED%95%A8%EC%88%98-promise-async-await\">동기/ 비동기의 이해 - callback함수, promise, async, await</a></li>\n<li><a href=\"https://satisfactoryplace.tistory.com/18\">콜백함수의 정확한 의미는 무엇일까?</a></li>\n<li><a href=\"https://dalkomit.tistory.com/65\">Callback 함수란 무엇인가?</a></li>\n<li><a href=\"https://koonsland.tistory.com/159\">콜백 함수 사용 방법</a></li>\n</ul>\n<p>async, await</p>\n<ul>\n<li><a href=\"https://velog.io/@pilyeooong/Promise%EC%99%80-asyncawait-%EC%B0%A8%EC%9D%B4%EC%A0%90\">Promise와 async/await 차이점</a></li>\n</ul>\n<p>Promise</p>\n<ul>\n<li><a href=\"https://velog.io/@pilyeooong/Promise%EC%99%80-asyncawait-%EC%B0%A8%EC%9D%B4%EC%A0%90\">Promise와 async/await 차이점</a></li>\n</ul>","frontmatter":{"title":"💻 동기 및 비동기 처리","date":"January 21, 2022","update":"January 21, 2022","tags":["Callback","Async","Await","Promise"],"series":"💻 BackEnd"},"fields":{"slug":"/[BackEnd]Sync&aSync/","readingTime":{"minutes":9.095}}},"seriesList":{"edges":[{"node":{"id":"08d09624-7fa6-5d93-9623-abb70d863931","fields":{"slug":"/[BackEnd]JWT/"},"frontmatter":{"title":"💻 JWT"}}},{"node":{"id":"fa6720c2-ab20-5a55-b914-bbf10ec8fda0","fields":{"slug":"/[BackEnd]Sync&aSync/"},"frontmatter":{"title":"💻 동기 및 비동기 처리"}}},{"node":{"id":"72a19297-193d-5bb7-895a-44f328517242","fields":{"slug":"/[BackEnd]REST/"},"frontmatter":{"title":"💻 REST"}}},{"node":{"id":"61c43f1b-d1df-5602-9b51-8fe6fa9d3b01","fields":{"slug":"/[BackEnd]객체지향생활체조/"},"frontmatter":{"title":"💻 객체지향 생활체조"}}},{"node":{"id":"871dad9f-422b-50ed-8c98-d441dc97e4d0","fields":{"slug":"/[BackEnd]Interceptor/"},"frontmatter":{"title":"💻 Interceptor"}}},{"node":{"id":"b945159a-d6ce-5269-a463-898869856e12","fields":{"slug":"/[BackEnd]Docker배포/"},"frontmatter":{"title":"💻 Docker를 이용한 Springboot 배포"}}},{"node":{"id":"4101ebe6-43c8-571b-b984-a63d64e55d2b","fields":{"slug":"/IoC와 DI/"},"frontmatter":{"title":"💬 IoC와 DI"}}},{"node":{"id":"80b1cfb1-9f95-5921-bac9-4c540ad89c1e","fields":{"slug":"/[Backend]WebServer&WAS/"},"frontmatter":{"title":"💻 Web Server와 WAS"}}}]},"previous":{"fields":{"slug":"/[BackEnd]JWT/"},"frontmatter":{"title":"💻 JWT"}},"next":{"fields":{"slug":"/[BOJ]9466/"},"frontmatter":{"title":"👩‍💻 9466. 텀 프로젝트"}}},"pageContext":{"id":"fa6720c2-ab20-5a55-b914-bbf10ec8fda0","series":"💻 BackEnd","previousPostId":"08d09624-7fa6-5d93-9623-abb70d863931","nextPostId":"01bbb6dc-812c-5223-87c5-53bf04c0d0a6"}},"staticQueryHashes":[]}